package band.wukong.practice.javase.core.thread.sync;

/**
 * Description: 死锁。本例会造成死锁
 * Author: jsun
 * Date: 2009-11-8 15:22:08
 */
public class TestDeadLock extends Thread {
    private Counter counter;    //共享数据

    public TestDeadLock(Counter counter) {
        this.counter = counter;
        start();
    }

    public void run() {
        for (int i = 0; i < 1000; i++) {
            counter.add();
        }
    }

    public static void main(String[] args) {
        Counter counter1 = new Counter();
        Counter counter2 = new Counter();
        counter1.setFriend(counter2);
        counter2.setFriend(counter1);

        TestDeadLock m1 = new TestDeadLock(counter1);
        TestDeadLock m2 = new TestDeadLock(counter2);
    }

    private static class Counter {
        private int a;
        private Counter friend;

        public void setFriend(Counter friend) {
            this.friend = friend;
        }

        public synchronized void add() {
            a++;
            Thread.yield();
            friend.delete();
            System.out.println(Thread.currentThread().getName() + ": add.");
        }

        public synchronized void delete() {
            a--;
            System.out.println(Thread.currentThread().getName() + ": delete.");
        }
    }
}
